using UnityEngine;
using UnityEditor;
using UnityEngine.SceneManagement;

namespace LCH
{
    /// <summary>
    /// 网格绘制器 - 生命周期功能模块
    /// </summary>
    public partial class LchMeshPainter
    {
        /// <summary>
        /// 绘制GUI界面
        /// </summary>
        public void OnGUI()
        {
            OnDrawMainPanel();
            HandleKeyboard();
            if (selectObject == null)
            {
                if (null != brush)
                {
                    GameObject.DestroyImmediate(brush, true);
                }
                if (null != rtCamera)
                {
                    GameObject.DestroyImmediate(rtCamera, true);
                }

            }
        }
        
        /// <summary>
        /// 场景切换时关闭窗口
        /// </summary>
        private void CloseSelf(Scene arg0, Scene arg1)
        {
            window.Close();
        }
        
        /// <summary>
        /// 场景卸载时关闭窗口
        /// </summary>
        private void CloseSelf1(Scene arg0)
        {
            window.Close();
        }
        
        /// <summary>
        /// 窗口禁用时清理资源
        /// </summary>
        public void OnDisable()
        {
            CheckUnSave();
            if (is2019OrNew)
            {
                SceneView.beforeSceneGui -= UpdateWindow;
                SceneManager.activeSceneChanged += CloseSelf;
                SceneManager.sceneUnloaded += CloseSelf1;
            }
            else
            {
               
                SceneView.onSceneGUIDelegate -= UpdateWindow;
               
                SceneManager.activeSceneChanged += CloseSelf;
                SceneManager.sceneUnloaded += CloseSelf1;
                
            }
 
            
            EditorApplication.update -= Update;
            ReleaseEditorObject();
            if (null != selectObjectMaterial && ctrlText != null)
            {
                // 保存所有控制图
                ControlTextureOperations.ApplyControlTexturesToMaterial(selectObjectMaterial, ctrlText, detectedCtrlTextureNames);
                if(null != flowMapTex)
                    selectObjectMaterial.SetTexture(setting.flowMapTextureName, flowMapTex);
            }
            // 释放控制图资源
            ControlTextureOperations.ReleaseControlTextures(ref ctrlText, ref editorCtrl1RT);
            if(null != editorFlowMapRT)
                GameObject.DestroyImmediate(editorFlowMapRT, true);
            texturePaninnerUndoRedo.Clear();
            vertexUndoRedo.Clear();
            uvAreaPerviewTexture.Clear();
            ReleaseBrush();
            if (null != selectObjectMesh)
            {
                selectObjectMesh.colors = baseColors;
            }
            SaveSetting();
            
        }

        /// <summary>
        /// 检查未保存的修改，提示用户保存
        /// </summary>
        void CheckUnSave()
        {
            if (isTextureChannelModify  )
            {
                isTextureChannelModify = false;
            
                if (EditorUtility.DisplayDialog("", Languages.GetValue(49,"Save Texture channels Modify?"), Languages.GetValue(47, "Yes"), Languages.GetValue(48, "No")))
                {
                    SaveTextures();
                }

            }
            if (isVertexDirty)
            {
                isVertexDirty = false;
                if (EditorUtility.DisplayDialog("", Languages.GetValue(50, "Save Vertex color Modify?"), Languages.GetValue(47, "Yes"), Languages.GetValue(48, "No")))
                {
                    string path = AssetDatabase.GetAssetPath(selectObjectMesh);
                    if (path.EndsWith(".mesh"))
                    {
                        selectObjectMesh.colors = baseColors;
                        EditorUtility.SetDirty(selectObjectMesh);
                    }
                    else
                    {
                        string _path = EditorUtility.SaveFilePanelInProject(Languages.GetValue(21, "Save mesh"), "mesh", "mesh", Languages.GetValue(22, "save mesh to your project"));
                        if (_path.Length > 0)
                        {
                            //Debug.LogError(_path);
                            Mesh m = (Mesh)GameObject.Instantiate(selectObjectMesh);
                            AssetDatabase.CreateAsset(m, _path);
                            selectObjectMesh = (Mesh)AssetDatabase.LoadAssetAtPath<Mesh>(_path);
                            selectObject.sharedMesh = selectObjectMesh;
                            baseColors = selectObjectMesh.colors;
                        }
                    }
                }
            }
             
        }
        
        /// <summary>
        /// 窗口启用时初始化
        /// </summary>
        public void OnEnable()
        {
            isTextureChannelModify = false;
            isVertexModify = false;
            LoadSetting();
            Languages.Init();
            LoadBrushs();

            if (null == brushTexture)
                brushTexture = new RenderTexture(2048, 2048, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
            if (is2019OrNew)
            {
                SceneView.beforeSceneGui -= UpdateWindow;
                SceneView.beforeSceneGui += UpdateWindow;
            }
            else
            {
                SceneView.onSceneGUIDelegate -= UpdateWindow;
                SceneView.onSceneGUIDelegate += UpdateWindow;
                
            }
 
            EditorApplication.update += Update;

        }
        
        /// <summary>
        /// 释放编辑器对象资源
        /// </summary>
        void ReleaseEditorObject()
        {
            ReleaseMeshCollider();
            if (null != brush)
                GameObject.DestroyImmediate(brush, true);
            if (null != brushTexture)
                GameObject.DestroyImmediate(brushTexture, true);
            if (null != rtCamera)
                GameObject.DestroyImmediate(rtCamera.gameObject, true);
            if (null != brushing)
                GameObject.DestroyImmediate(brushing, true);
            terrainTools.Release();
            previewHelper.Release();

            ReleaseIcons();

        }
        
        /// <summary>
        /// 添加修改到撤销/重做系统
        /// </summary>
        void AddModify()
        {
            if (isTextureFlowMaplDirty || isTextureChannelDirty)
            {
                Texture fm = editorFlowMapRT;
                if (null == fm)
                    fm = flowMapTex;
                Texture[] ts = editorCtrl1RT;
                if (ts == null)
                    ts = ctrlText;
                texturePaninnerUndoRedo.Add(ts, fm);
                
            }
            isTextureChannelDirty = false;
            isTextureFlowMaplDirty = false;
            dirtyTime = 0f;

        }
        
        /// <summary>
        /// 更新绘制器面板逻辑
        /// </summary>
        void UpdatePainterPanel()
        {
            DrawBrushTexture();
            if (flowMapEditing)
            {
                if (textureNeedPaint)
                {
                    OnPlaintFlowMap();
                    textureNeedPaint = false;
                    isTextureChannelModify = true;
                }
                if (isTextureFlowMaplDirty)
                {
                    isTextureChannelModify = true;
                    if (isDragging)
                    {
                        dirtyTime = 0f;
                    }
                    else
                    {
                        dirtyTime += Time.deltaTime;
                    }
                    if (dirtyTime > 1f)
                    {
                        AddModify();
                    }
                }

            }
            else
            {
                if (textureNeedPaint)
                {
                    OnPlaint();
                    textureNeedPaint = false;
                }
                if (isTextureChannelDirty)
                {
                    isTextureChannelModify = true;
                    if (isDragging)
                    {
                        dirtyTime = 0f;
                    }
                    else
                    {
                        dirtyTime += Time.deltaTime;
                    }
                    if (dirtyTime > 1f)
                    {
                        AddModify();
                    }
                }
                
            }

            if (isVertexDirty)
            {

                isVertexModify = true;
                if (isDragging)
                {
                    dirtyTime = 0f;
                }
                else
                {
                    dirtyTime += Time.deltaTime;
                }
                if (dirtyTime > 1f)
                {
                    isVertexDirty = false;
                    if (null != selectObjectMesh)
                        vertexUndoRedo.Add(selectObjectMesh.colors);
                }
            }
            if (vertexNeedPaint)
            {
                OnPlaintVertex();
                vertexNeedPaint = false;
            }
            if (!textureNeedPaint && !vertexNeedPaint)
            {
                window.Repaint();
            }

        }
        
        /// <summary>
        /// 每帧更新
        /// </summary>
        private void Update()
        {
            if (null == selectObject)
            {
                selectObjectMesh = null;
            }
            else
            {
                selectObjectMesh = selectObject.sharedMesh;
            }
            if (selectObjectMesh != lastSelectObjectMesh)
            {
                lastSelectObjectMesh = selectObjectMesh;
                OnSelectedMeshChange();
            }
            uvAreaPerviewTexture.Update ();

            if (enable)
            {

                switch (panelType)
                {
                    case 0:
                        {

                            UpdatePainterPanel();
                        }
                        break;
                    case 2:
                        {
                            UpdateBuildingTree();
                        }
                        break;
                }

            }
            SceneView.RepaintAll();
            
        }
        
        /// <summary>
        /// 更新建筑树工具
        /// </summary>
        void UpdateBuildingTree()
        {
            
        }
        
        /// <summary>
        /// 选择的网格改变时的处理
        /// </summary>
        void OnSelectedMeshChange()
        {
            vertexUndoRedo.Clear();
            if (selectObjectMesh == null)
            {
                baseColors = null;
            }
            else
            {
                baseColors = selectObjectMesh.colors;
                vertexUndoRedo.Add(baseColors);
            }
        }
    }
}

